﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using BasecampRestAPI;

namespace MoveToDoList
{
	public class MainFormMediator
	{
		private IBaseCamp _camp;
		private readonly IMainForm _form;
		private IProject[] _projects;
		private IToDoList[] _sourceLists;
		private IToDoList[] _targetLists;

		public static MainFormMediator GetInstance(IMainForm form)
		{
			return new MainFormMediator(form);
		}
		private MainFormMediator(IMainForm form)
		{
			_form = form;
		}

		public void Load()
		{
			if (!_form.GetBaseCampFromCredentials(out _camp))
			{
				return;
			}
			List<string> names = new List<string>();
			List<IProject> projects = new List<IProject>();
			foreach (IProject project in _camp.Projects)
			{
				names.Add(project.Name);
				projects.Add(project);
			}
			_projects = projects.ToArray();
			Array.Sort(names.ToArray(), _projects);
			foreach (IProject project in _projects)
			{
				_form.SourceProject.AddProject(project.Name);
				_form.TargetProject.AddProject(project.Name);
			}
			_form.SourceProject.ProjectSelectedIndex = 0;
			_form.TargetProject.ProjectSelectedIndex = 0;
		}

		public void SourceProjectSelectedIndexChanged()
		{
			ProjectSelectedIndexChanged(ref _sourceLists, _form.SourceProject);
		}

		public void TargetProjectSelectedIndexChanged()
		{
			ProjectSelectedIndexChanged(ref _targetLists, _form.TargetProject);
		}

		private void ProjectSelectedIndexChanged(ref IToDoList[] toDoLists, IProjectToDoLists projectToDoLists)
		{
			List<string> listNames = new List<string>();
			toDoLists = _projects[projectToDoLists.ProjectSelectedIndex].ToDoLists;
			foreach (IToDoList list in toDoLists)
			{
				listNames.Add(list.Name);
			}
			Array.Sort(listNames.ToArray(), toDoLists);
			projectToDoLists.ClearToDoLists();
			foreach (IToDoList list in toDoLists)
			{
				projectToDoLists.ToDoListsAddItem(list.Name);
			}
		}

		public void MoveButtonClick()
		{
			Cursor cursor = _form.Cursor;
			try
			{
				_form.Cursor = Cursors.WaitCursor;
				ListMover mover = ListMover.GetInstance(_projects[_form.TargetProject.ProjectSelectedIndex]);
				foreach (int index in _form.SourceProject.SelectedLists)
				{
					IToDoList sourceList = _sourceLists[index];
					IToDoList newList = mover.CopyToDoList(sourceList);
					_form.TargetProject.ToDoListsAddItem(newList.Name);
				}
			}
			finally
			{
				_form.Cursor = cursor;
			}
		}

		public void DeleteButtonClick()
		{
			Cursor cursor = _form.Cursor;
			try
			{
				_form.Cursor = Cursors.WaitCursor;
				foreach (int index in _form.SourceProject.SelectedLists)
				{
					_sourceLists[index].Delete();
				}
				ProjectSelectedIndexChanged(ref _sourceLists, _form.SourceProject);
			}
			finally
			{
				_form.Cursor = cursor;
			}
		}
	}
}
